import React from 'react'
import { contentChange, reOrder, switchTo, focusElm, draging, draged, edited, editing, resized, resizing, styleChange, undo, redo, deleteElm, addTextElm } from '../actions/content-change'
import Page from './card-page.jsx'
import { analysisSvg } from '../utils.js'
import { connect } from 'react-redux'
import F, { compose } from 'lodash/fp'
import Editor from './decorator/wang-editor.jsx'
import Ctrl from './decorator/ctrl.jsx'

class Card extends React.Component {
    // shouldComponentUpdate(nextProps) {
    //     return nextProps.target !== 'Card'
    // }

    render() {

        return (
            <div className="card-editor" style={{width: `${SCALE * 320}px`, height: `${SCALE * 486}px`, marginTop: `${($('body').height() - 90 - SCALE * 486) / 2}px`}}>
                <Editor {...this.props} />
                <Ctrl {...this.props} />
                <div className="modal-wp" id="card" style={{ 
                    transform: `matrix(${SCALE}, 0, 0, ${SCALE}, 0, 0`,
                    transformOrigin: `top ${SCALE > 1 ? 'center' : 'left'}`,
                }}>
                    <div
                        onMouseMove={ev => {
                            let $focus = $('.decorator.active').parents('.elm-box')
                            let get = attr => parseInt($focus.css(attr))
                            if (this.props.isDraging) {
                                $focus.css('transform', `translate(${Math.ceil((ev.screenX - this.props.dragOffset.x) / SCALE)}px, ${Math.ceil((ev.screenY - this.props.dragOffset.y) / SCALE)}px)`)
                            }

                            if (this.props.isResizing) {
                                let { x, y, w, h, t, l, dot } = this.props.resize
                                let offsetX = (ev.screenX - x) / SCALE
                                    , offsetY = (ev.screenY - y) / SCALE

                                if (dot === 1 || dot === 2 || dot === 3) h -= offsetY, t += offsetY

                                if (dot === 3 || dot === 4 || dot === 5) w += offsetX

                                if (dot === 5 || dot === 6 || dot === 7) h += offsetY

                                if (dot === 7 || dot === 8 || dot === 1) l += offsetX, w -= offsetX

                                let resize =
                                    {
                                        width: `${Math.max(w, 42)}px`
                                        , height: `${Math.max(h, 26)}px`
                                        , left: `${Math.min(l, this.props.resize.l + this.props.resize.w - 42)}px`
                                        , top: `${Math.min(t, this.props.resize.t + this.props.resize.h - 26)}px`
                                    }

                                {/*this.props.styleChange(this.props.focus, resize)*/ }
                                $focus.css(resize)
                            }
                        }}
                        style={{
                            transform: `matrix(1, 0, 0, 1, 0, -${this.props.activeIndex * 486})`,
                        }}
                    >
                        {this.props.pages.map((t, i) => <Page
                            elements={t.elements}
                            key={t.id}
                            path={i}
                            onInput={this.props.onInput}
                            isEditable
                            selectedPath={this.props.selectedPath}
                            focusElm={this.props.focusElm}
                            focused={this.props.focus}
                            draging={this.props.draging}
                            editing={this.props.editing}
                            edited={this.props.edited}
                            isEditing={this.props.isEditing}
                            resizing={this.props.resizing}
                        />)}
                    </div>
                </div>
            </div>
        )
    }
}

$(window).on('mouseup', () => {
    let { isDraging, isResizing, focus, isEditing } = store.getState().card
    if (isDraging) {
        store.dispatch(draged())
        let $focus = document
            .querySelector('.decorator.active')
            .parentElement

        if (!$focus.style.transform) return;

        let [x, y] = $focus
            .style
            .transform
            .match(/([-\.\d]+)/g)
            .map(Math.ceil)

        $focus = $($focus)

        //react 重新渲染时并不会重置 transform属性
        $focus.css('transform', '')

        store.dispatch(styleChange(focus, { left: `${parseInt($focus.css('left')) + x}px`, top: `${parseInt($focus.css('top')) + y}px` }))
        store.dispatch(draged())
    }

    if (isResizing) {
        let need = ['width', 'height', 'top', 'left']
            , mergeStyle = {}
            , $focus = $('.decorator.active').parents('.elm-box')

        for (let i = 0; i < need.length; i++) {
            mergeStyle[need[i]] = $focus.css(need[i])
        }
        store.dispatch(styleChange(focus, mergeStyle))
        store.dispatch(resized())
    }
})
.on(BROWSER.mouseDown, function () {
    let { isDraging, isResizing, focus, isEditing } = store.getState().card
    if (isEditing) {
        store.dispatch(contentChange($('#wang-editor').html(), focus.split('.')))
        store.dispatch(edited())
    }
})
.on('keydown', function (e) {
    let { isDraging, isResizing, focus, isEditing } = store.getState().card
    if (e.ctrlKey && e.keyCode === 90) {
        store.dispatch(undo())
    }
    if (e.ctrlKey && e.keyCode === 89) {
        store.dispatch(redo())
    }
    if (focus && !isEditing && e.keyCode === 46) {
        store.dispatch(deleteElm([focus]))
    }
})

export default connect(
    state => state.card,
    (dispatch, props) => ({
        onInput: (content, path) => dispatch(contentChange(content, path, 'Card')),
        focusElm: compose(dispatch, focusElm),
        draging: compose(dispatch, draging),
        editing: compose(dispatch, editing),
        edited: compose(dispatch, edited),
        resizing: compose(dispatch, resizing),
        styleChange: compose(dispatch, styleChange),
        addTextElm: compose(dispatch, addTextElm),
        undo: compose(dispatch, undo),
        redo: compose(dispatch, redo),
        deleteElm: function(e) {
            layer.confirm('你确定要删除吗？', function(index){
                F.compose(dispatch, deleteElm)(e)
                layer.close(index)
            })
        },
    })
)(Card)
